import time
from tkinter import *

from spider import start


class Application(Frame):
    ipad = None

    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.createWidget()
        self.line_num = 0

    def createWidget(self):
        Label(self, text="爬取的链接", width=8, height=3, justify=LEFT).pack(side=LEFT)
        url = StringVar()
        self.urlInput = Entry(self, width=70, textvariable=url)
        self.urlInput.pack(side=LEFT)
        Button(self, text="开始爬取", command=self.start).pack(side=LEFT)
        # Button(self, text="停止爬虫", command=self.stop).pack(side=LEFT)
        # self.ipad = Text(root, width=200, height=470)
        # self.ipad.pack()

    def start(self):
        url = self.urlInput.get()
        print(url)
        start(url)
        # self.ipad.insert(1.0, self.urlInput.get())
        # self.write_log_to_text(self.urlInput.get())

    def stop(self):
        print("停止")

    def write_log_to_text(self, msg):
        current_time = self.get_current_time()
        msg = str(current_time) + " " + str(msg) + "\n"
        # 从最后插入
        self.ipad.insert(END, msg + "\n")
        self.line_num = self.line_num + 1
        print(self.line_num)
        if self.line_num > 17:
            self.ipad.delete(1.0, 3.0)
            self.line_num = self.line_num - 1

    # 获取当前时间
    def get_current_time(self):
        current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        return current_time


root = Tk()
root.geometry("650x100+400+300")
root.title("爬虫")
app = Application(master=root)

root.mainloop()
